Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Amazon Hard Problems
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Number of Valid Subarrays

Problem Statement

Given an integer array nums, return the total count of non-empty subarrays within nums where each subarray must have its first element as the smallest among all its elements.

A subarray is a Contiguous part of an array.

Examples

  • Example 1:

    • Input: nums = [4, 3, 1]
    • Expected Output: 3
    • Justification: The valid subarrays are [4], [3], and [1]. Each subarray consists of a single element, satisfying the condition since there's no smaller element than the first.
  • Example 2:

    • Input: nums = [1, 3, 2, 4, 1]
    • Expected Output: 10
    • Justification: The valid subarrays are [1], [1, 3], [1, 3, 2], [1, 3, 2, 4], [1, 3, 2, 4, 1], [3], [2], [2, 4], [4], and [1].
  • Example 3:

    • Input: nums = [3, 3, 3]
    • Expected Output: 6
    • Justification: The valid subarrays are [3], [3], [3], [3, 3], [3, 3], and [3, 3, 3]. Since all elements are equal, all subarrays starting with any element satisfy the condition.

Solution

To solve this problem, we can use a stack to keep track of elements in a way that helps us quickly determine the number of valid subarrays ending with each element of the array. The crux of this approach lies in understanding that a valid subarray can be extended by elements larger than or equal to its first element without violating the condition. This makes a stack an ideal data structure for maintaining a sequence of elements where each new element can potentially form new valid subarrays with the preceding ones.

Our approach is effective because it efficiently iterates through the array once, leveraging the stack to manage the elements in a way that minimizes unnecessary comparisons. Each element is pushed onto the stack only once and popped only once, ensuring that we keep our operations to a minimum while accurately counting the valid subarrays.

Step-by-step Algorithm

  1. Initialize a Stack: Start by creating an empty stack. This stack will be utilized to store the indices of elements from the input array nums. The stack helps in tracking the elements that are in non-decreasing order from the current index being processed.

  2. Initialize Count Variable: Set up a variable, count, to keep a cumulative total of valid subarrays discovered throughout the iteration of the array. Initialize count to 0.

  3. Iterate Through the Array:

    • Loop over each element in nums using an index variable i. For each i, perform the following:
      • Maintain Stack for Non-Decreasing Order: While the stack is not empty and the element at nums[stack.peek()] is greater than nums[i], pop elements from the stack. This ensures that the stack only contains indices of elements that are in non-decreasing order up to the current index i.
      • Push Current Index onto Stack: Push the current index i onto the stack. This action signifies that nums[i] is now the last element of a valid subarray ending at i.
      • Update Count: Increment the count by the current size of the stack. The size of the stack represents the number of valid subarrays that end at the current element.
  4. Return the Total Count: After completing the iteration over the array, return the count variable. This variable now contains the total number of valid subarrays within nums.

Algorithm Walkthrough

Let's consider the Input: nums = [1, 3, 2, 4, 1].

  • Start: stack = [], count = 0

  • i=0 (nums[i] = 1):

    • Stack is empty, so push 0.
    • stack = [0]
    • Increment count by stack size (1).
    • count = 1
  • i=1 (nums[i] = 3):

    • 3 is greater than 1 (nums[stack.peek()]), so push 1.
    • stack = [0, 1]
    • Increment count by stack size (2).
    • count = 3
  • i=2 (nums[i] = 2):

    • 2 is less than 3 (nums[stack.peek()]), pop 1.
    • stack = [0], then push 2.
    • stack = [0, 2]
    • Increment count by stack size (2).
    • count = 5
  • i=3 (nums[i] = 4):

    • 4 is greater than 2 (nums[stack.peek()]), so push 3.
    • stack = [0, 2, 3]
    • Increment count by stack size (3).
    • count = 8
  • i=4 (nums[i] = 1):

    • 1 is less than 4 (nums[stack.peek()]), pop 3.
    • 1 is less than 2 (nums[stack.peek()]), pop 2.
    • stack = [1], then push 4.
    • stack = [1, 4]
    • Increment count by stack size (2).
    • count = 10

The final count after the loop is 10.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where (n) is the length of the input array nums. This efficiency is achieved because each element in the array is processed exactly once when it is pushed onto the stack and at most once when it is popped from the stack.

Space Complexity

The space complexity is in the worst case. This worst-case scenario occurs when the input array is sorted in non-decreasing order, causing all elements to be pushed onto the stack before any are popped.

Number of Valid Subarrays (hard)
Count Vowels Permutation (hard)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity